<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/15
 * Time: 17:16
 */

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @property Ga_goods_model ga_goods_model
 * @property Admin_model  admin_model
 */
class SalesCount extends Admin_Controller
{


    public function index()
    {

        $this->load->model('ga_goods_model');
        $this->load->model('goods_model');
        $this->load->model('admin_model');
        $this->load->model('suppliers_model');

        $assoc = $this->uri->uri_to_assoc();

        $se_arr = array(
            'siteweb' => $this->ga_goods_model->siteweb_option(),
            'admin' => $this->admin_model->admin_option(),
            'supp' => $this->suppliers_model->suppliers_option(),
            'cate' => $this->ga_goods_model->cate()
        );

        $json_data = $this->goods_items(
            array(
                'admin' => $this->admin_model->admin_option()
            )
        );

        $data = array(
            'se_arr' => $se_arr,
            'goods_list' => json_encode(array_values($json_data['rows'])),
            'param' => $json_data['param'],
            'ga_goods' => $json_data['ga_goods'],
            'goods_ids' => $json_data['goods_ids'],
            'param' => $json_data['param'],
            'pages' => $json_data['pages']
        );

        $this->load->view('sales_count', $data);
    }

    public function ajax_goods_list()
    {

        $this->load->model('admin_model');

        $data = $this->goods_items(
            array(
                'admin' => $this->admin_model->admin_option()
            )
        );

        $data['rows'] = array_values($data['rows']);

        echo json_encode($data);
        exit;
    }

    private function goods_items($se_arr = array())
    {
        $this->load->model('ga_goods_model');
        $this->load->model('goods_model');
        $this->load->model('admin_model');
        $this->load->model('suppliers_model');

        $this->load->library('pagination');

        $assoc = $this->uri->uri_to_assoc();

        $_param = array(
            'web_id' => array_filter(explode('_', trim($assoc['web_id']))),
            'is_on_sale' => intval($assoc['is_on_sale']) ? intval($assoc['is_on_sale']) : 2,
            'goods_sn' => array_filter(explode('%20', trim($assoc['goods_sn']))),
            'sale_count' => intval($assoc['sale_count']) ? intval($assoc['sale_count']) : 3,
            'cate_id' => array_filter(explode('_', $assoc['cate_id'])),
            'admin_id' => intval($assoc['admin_id']),
            'suppliers_id' => intval($assoc['suppliers_id']),
            'on_sale_time' => explode('_', trim($assoc['on_sale_time'])),
            'statistical_time' => explode('_', trim($assoc['statistical_time'])),
            'll_info' => explode('_', trim($assoc['ll_info'])),
            'jc_info' => explode('_', trim($assoc['jc_info'])),
            'zh_info' => explode('_', trim($assoc['zh_info'])),
            'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0
        );

        //$config['base_url'] = base_url('SalesCount/index/page/');
        $_param['goods_ids'] = $this->ga_goods_model->goods_sum_filter($_param);

        $config['total_rows'] = $this->ga_goods_model->goods_count($_param);
        $config['num_links'] = 6;
        $config['per_page'] = $this->goods_model->limit_rows;
        $config['use_page_numbers']=true;
        $this->pagination->initialize($config);


        $goods_list = $this->ga_goods_model->goods_list($_param);

        $arr_goods_ids = array_column($goods_list, 'goods_id');

        $goods_ids = implode('_', $arr_goods_ids);

        $_param['goods_ids'] = $arr_goods_ids;

        $ga_goods = $this->ga_goods_model->ga_goods_list($_param);

        $_list = array();
        $i = 1;

        foreach ($goods_list as $item) {
            $_list[$item['goods_id']] = array(
                'open' => '<img class="detail-open" data-id="' . $item['goods_id'] . '" src="/public/images/details_open.png">',
                'goods_id' => ($_param['page'] * $this->ga_goods_model->limit_rows) + $i,
                'original_img' => '<img src="' . $item['original_img'] . '" width="40">',
                'goods_info' => '<p>' . $item['cate_name'] . '</p><p>' . $item['goods_sn'] . '</p>' . '<p>' . ($item['is_on_sale'] ? '在售' : '下架') . '</p>',
                'purchase_info' => '<p>采买</p><p>开发: ' . ($item['admin_id'] ? $se_arr['admin'][$item['admin_id']] : '无') . '</p><p>刘达</p><p style=" width: 150px; height: 18px; line-height: 18px; overflow:hidden;">供应商: <span >' . $item['suppliers_name'] . '</span></p><p>成本: ' . $item['in_price'] . '</p>',
                'on_sale_info' => '<div class="goods_num goods-' . $item['goods_id'] . '"></div><a href="#myModal-' . $item['goods_id'] . '" data-toggle="modal" class="btn btn-info btn-xs ajax-but" data-id="' . $item['goods_id'] . '" >查看走势图</a><a href="#myCountry-' . $item['goods_id'] . '" data-toggle="modal" class="btn btn-info btn-xs ajax-but" data-id="' . $item['goods_id'] . '" >查看国家</a>',
                'country_order' => '<div class="country_num country-goods-' . $item['goods_id'] . '"></div><a href="#myCountry-' . $item['goods_id'] . '" data-toggle="modal" class="btn btn-info btn-xs ajax-but" data-id="' . $item['goods_id'] . '" >查看国家</a>',
                'inventory_info' => '<div class="inventory_num inventory-' . $item['goods_id'] . '"></div>',
                'sales_info' => '<p class="sale_count">销售额：' . $item['goods_num_price'] . '</p>',
                'data_info' => '<p>浏览量</p><p>加车率</p><p>转化率</p><p>销量</p>'
            );


            foreach ($ga_goods['data'][$item['goods_id']] as $k => $ga_item) {

                $_list[$item['goods_id']][$k] = "<p>{$ga_item['detail_views']}</p>";
                $_list[$item['goods_id']][$k] .= "<p>" . ($ga_item['adds_cart'] > 0 ? ($ga_item['detail_views'] > 0 ? (sprintf('%.4f',  $ga_item['adds_cart'] / $ga_item['detail_views']) * 100 . '%') : ($ga_item['adds_cart'] * 100 . '.00%')) : '0.00%') . "</p>";
                $_list[$item['goods_id']][$k] .= "<p>" . ($ga_item['item_quantity'] > 0 ? ($ga_item['detail_views'] > 0 ? (sprintf('%.4f',  $ga_item['item_quantity'] / $ga_item['detail_views']) * 100 . '%') : ($ga_item['order_quantity'] * 100 . '.00%')) : '0.00%') . "</p>";
                $_list[$item['goods_id']][$k] .= "<p>{$ga_item['item_quantity']}</p>";
            }
            $i++;
        }



        $data = array(
            'goods_ids' => $goods_ids,
            'param' => $_param,
            'rows' => $_list,
            'ga_goods' => $ga_goods,
            'pages' => $this->pagination->create_links()
        );

        return $data;
    }

    public function ajax_sku_list()
    {
        $this->load->model('ga_goods_model');
        $assoc = $this->uri->uri_to_assoc();

        $goods_id = intval($assoc['goods_id']);

        $sku_list = $this->ga_goods_model->goods_sku_list(array(
            'goods_id' => $goods_id
        ));

        echo json_encode($sku_list);
        exit;

    }

    public function product_inventory()
    {

        $this->load->library('eccang');
        $this->load->model('ga_goods_model');
        $assoc = $this->uri->uri_to_assoc();

        $goods_ids = explode('_', trim($assoc['goods_ids']));

        $goods_sku = $this->ga_goods_model->goods_sku($goods_ids);

        $_sku_sn = array_column($goods_sku, 'sku_sn');

        $sku_sn = array();
        foreach ($_sku_sn as $val) {
            $sku_sn[] = str_replace(array('/', '&'), '', $val);
        }

        $_product = $this->eccang->getProductInventory(array(
            'productSkuLike' => $sku_sn,
            'pageSize' => 1000
        ));

        $product = array();
        foreach ($_product as $row) {
            $product[$row['productSku']] = $row;
        }

        $goods = array();
        foreach ($goods_sku as $item) {
            $item['sku_sn'] = str_replace(array('/', '&'), '', $item['sku_sn']);

            $inventory = $product[strtoupper($item['sku_sn'])];

            $goods[' ' . $item['goods_id']][$item['sku_id']] = $inventory;
        }

        echo json_encode($goods);
        exit;
    }

    public function siteweb_goods_sale()
    {
        $this->load->model('ga_goods_model');
        $assoc = $this->uri->uri_to_assoc();

        $goods_ids = explode('_', trim($assoc['goods_ids']));
        $goods_id = intval($assoc['goods_id']);

        $goods_sku = $this->ga_goods_model->goods_sale(array(
            'goods_ids' => $goods_ids,
            'goods_id' => $goods_id
        ));

        echo json_encode($goods_sku);
        exit;

    }

    public function purchase_orders()
    {
        $this->load->library('eccang');

        $this->load->model('goods_model');

        $assoc = $this->uri->uri_to_assoc();

        $goods_id = intval($assoc['goods_id']);

        $goods = $this->goods_model->goods_info($goods_id);

        $goods_sn = strstr($goods['goods_sn'], 'ML') ? "{$goods_id}-" : $goods['goods_sn'];

        $_pur = $this->eccang->getPurchaseOrders(array(
            'sku_type' => 2,
            'productCode' => $goods_sn,
            'po_staus' => 3,
            'pageSize' => 1000
        ));

        $_pur2 = $this->eccang->getPurchaseOrders(array(
            'sku_type' => 2,
            'productCode' => $goods_sn,
            'po_staus' => 5,
            'pageSize' => 1000
        ));

        $purchase = array();
        $_purchase = array_merge($_pur['data'], $_pur2['data']);

        $today = strtotime('today');
        foreach ($_purchase as $k => $item) {
            $purchase[$k]['po_code'] = $item['po_code'];
            $purchase[$k]['date_create'] = date('Y-m-d', strtotime($item['date_create']));
            $purchase[$k]['day'] = ($today - strtotime($purchase[$k]['date_create'])) / (24 * 3600);
            $purchase[$k]['supplier_name'] = urldecode($item['supplier_name']);
            foreach ($item['detail'] as $detail) {
                if (strstr($detail['product_sku'], $goods_sn)) {
                    $purchase[$k]['detail'][$detail['product_sku']]['qty_expected'] += $detail['qty_expected'];
                    $purchase[$k]['detail'][$detail['product_sku']]['qty_receving'] += $detail['qty_receving'];
                }

            }
        }

        echo json_encode($purchase);
        exit;
    }

    public function graph_ga_data() {
        $this->load->model('ga_goods_model');
        $assoc = $this->uri->uri_to_assoc();

        $goods_id = intval($assoc['goods_id']);
        $start_time = trim($assoc['start_time']);
        $end_time = trim($assoc['end_time']);

        $ga_list = $this->ga_goods_model->web_ga_goods($goods_id, array(
            'start_time' => $start_time,
            'end_time' => $end_time
        ));

        echo json_encode($ga_list);
        exit;
    }

    public function ajax_country_order()
    {
        $this->load->model('ga_goods_model');

        $assoc = $this->uri->uri_to_assoc();

        $goods_ids = explode('_', trim($assoc['goods_ids']));
        $web_ids = explode('_', trim($assoc['web_ids']));

        $order_list = $this->ga_goods_model->country_order($goods_ids, $web_ids);

        echo json_encode($order_list);
        exit;
    }

    public function total_sales()
    {

        $this->load->model('siteweb_model');
        $this->load->model('admin_model');
        $this->load->model('goods_model');

        $this->load->library('pagination');

        $assoc = $this->uri->uri_to_assoc();

        $admin = $this->db->from('admin')->where(['group'=>1,'is_del'=>0])->select('admin_id,admin_name')->get()->result_array();
        foreach ($admin as $key => $value) {
            $res[$value['admin_id']] = $value['admin_name'];
        }
        $_param_option = array(
            'admin_id' => array(
                'col' => 'col-lg-2',
                'type' => 'siteweb',
                'placeholder' => '管理员',
                'option' =>$res
            ),
            
        );

        $_param = array(
            'admin_id' => trim($this->input->get('admin_id'))
        );
        $dev_goods = $this->goods_model->developer_goods_sale($_param);
        $data = array(
            'param_option' => $_param_option,
            'admin' => $admin,
            'dev_goods' => $dev_goods,
            'param' => $_param,
        );

        $this->load->view('total_sales', $data);
    }

    // public function total_sales(){

    //     //分类
    //     $this->load->model('category_model');
    //     $category = $this->category_model->cate_option();
    //     //站点
    //     $this->load->model('siteweb_model');
    //     $siteweb = $this->siteweb_model->siteweb_option();
    //     //页面下拉框返回数据
    //     $_param_option = array(
    //         'type_time' => array(
    //             'col' => 'col-lg-2',
    //             'type' => 'option',
    //             'placeholder' => '请选择时间类型',
    //             'option' => array(
    //                 1 => '上架时间',
    //                 2 => '上传时间'
    //             )
    //         ),
    //         'goods_time' => array(
    //             'col' => 'col-lg-4',
    //             'type' => 'dpd_time',
    //             'placeholder' => '时间'
    //         ),
    //         'cat' => array(
    //             'col' => 'col-lg-2',
    //             'type' => 'cal_option',
    //             'placeholder' => '全部分类',
    //             'option' =>$category
    //         ),
    //         'web' => array(
    //             'col' => 'col-lg-2',
    //             'type' => 'siteweb',
    //             'placeholder' => '全部站点',
    //             'option' =>$siteweb
    //         ),
            
    //     );

    //     $_param = array(
    //         'goods_time_start' => trim($this->input->get('goods_time_start')),
    //         'goods_time_end' => trim($this->input->get('goods_time_end')),
    //         'type_time' => trim($this->input->get('type_time')),
    //         'cat' => trim($this->input->get('cat')),
    //         'web' => trim($this->input->get('web'))
    //     );
    //     $this->load->model('goods_model');
    //     $dev_goods = $this->goods_model->developer_goods_sale($_param);


    //     $data = array(
    //         'param_option' => $_param_option,
    //         'siteweb' => $siteweb,
    //         //'admin' => $admin,
    //         'dev_goods' => $dev_goods,
    //         'param' => $_param,
    //         //'res_sum' => $res_sum
    //     );

    //     $this->load->view('total_sales', $data);
    // }

    public function export_sku()
    {
        $this->load->model('goods_sku_model');

        $goods_sku = $this->goods_sku_model->sku_list(array('group_by' => array('gs.goods_id', 'gs.color'), 'order_by' => 'g.add_time ASC'), 1);

        $data = "序列,图片,货号,产品状态,产品来源,上架时间,当前时间,在售时间,分类,售价,SKU,标题\n";
        foreach ($goods_sku as $k => $row) {

            $i = $k+1;
            $date = date('Y/m/d', $row['add_time']);
            $data .= "{$i},{$row['original_img']},{$row['goods_sn']},,MULAN,{$date},,,{$row['cate_name']},{$row['shop_price']},{$row['sku_num_sn']},{$row['goods_name']}\n";
        }

        $filename = 'export_goods-' . date('YmdHis',  time()).'.csv';
        header("Content-Type: application/vnd.ms-excel; charset=GB2312");
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Transfer-Encoding: binary ");
        $csvContent = iconv("utf-8","gb2312",$data);

        echo $csvContent;
        exit;
    }

    public function export_goods_fb_feed()
	{
		$this->load->model('goods_model');
		$this->load->model('shopify_goods_model');
		$this->load->model('siteweb_model');

		$assoc = $this->uri->uri_to_assoc();

		$web_id = intval($assoc['web_id']);
		$siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $web_id));



	}

    public function export_order()
    {
        $this->load->model('order_model');
        $this->load->model('goods_model');
        $this->load->model('order_goods_model');
        $this->load->model('siteweb_model');

        $assoc = $this->uri->uri_to_assoc();

        $param['start_time'] = ($assoc['start_time'] ? strtotime($assoc['start_time']) : strtotime('yesterday'));
        $param['end_time'] = $assoc['end_time'] ? strtotime($assoc['start_time']) : ($param['start_time'] + 3600*24);

        $order_goods = $this->order_goods_model->goods_sales($param);

        $data = "订单号,订单金额,SKU,产品价格,landing_site,referring_site,source,medium,content,下单时间\n";

        foreach ($order_goods as $item) {
            $add_time = date('Y-m-d H:i:s', $item['add_time']);
            $urlarr = parse_url($item['landing_site']);
            parse_str($urlarr['query'],$parr);

            $data .= "{$item['order_sn']},{$item['order_amount']},{$item['sku_num_sn']},{$item['goods_price']},{$item['landing_site']},{$item['referring_site']},{$parr['utm_source']},{$parr['utm_medium']},{$parr['utm_content']},{$add_time}\n";
        }

        $filename = 'export_order_goods_' . $assoc['start_time'] .'.csv';
        header("Content-Type: application/vnd.ms-excel; charset=GB2312");
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Transfer-Encoding: binary ");
        $csvContent = iconv("utf-8","gb2312",$data);

        echo $csvContent;
        exit;
    }
}
